/*
 * Copyright (c) 2011  Cristian Constantin
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package com.quizio.mvc.util;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

/**
 * Handles return values of methods annotated with the {@link Json} annotation.
 * <p/>
 * The return value object is serialized in JSON format using Jackson library.
 *
 * @author Cristian Constantin
 * @since 12/16/11
 */
public class JsonMethodReturnValueHandler implements HandlerMethodReturnValueHandler {

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return returnType.getMethod().isAnnotationPresent(Json.class);
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

        //TODO: reuse ObjectMapper object between requests.

        webRequest.getNativeResponse(HttpServletResponse.class).setContentType("application/json");

        ObjectMapper objectMapper = new ObjectMapper();

        objectMapper.setSerializationConfig(
                objectMapper.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd")));

        Json annotation = returnType.getMethod().getAnnotation(Json.class);

        if (annotation.value().length > 0) {

            objectMapper.getSerializationConfig().setSerializationView(annotation.value()[0]);
        }

        objectMapper.writeValue(webRequest.getNativeResponse(HttpServletResponse.class).getOutputStream(), returnValue);
    }
}
